/**   
* @Title: HttpUploadFile.java 
* @Package test 
* @Description: TODO 
* @author mazhongrui  
* @date 2021年4月23日 下午4:01:39 
* @version    
*/
package com.xoa.util.archive;

/** 
 * @ClassName: HttpUploadFile 
 * @Description: TODO
 * @version  
 */

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

import java.io.*;

public class HttpUploadFile {
	
	private static final int TIMEOUT = 5000;
	
	public static String fileUpload(String url, File file) {
        String body = "{}";
        if (url == null || url.equals("")) {
            return "illegal";
        }
        if (!file.exists()) {
            return "file not exist";
        }
        PostMethod postMethod = new PostMethod(url);
        BufferedReader br = null;
        try {            
            // FilePart：用来上传文件的类,file即要上传的文件
            FilePart fp = new FilePart("file", file);
            Part[] parts = { fp };
            // 对于MIME类型的请求，httpclient建议全用MulitPartRequestEntity进行包装
            MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(mre);
            HttpClient client = new HttpClient();
            // 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间
            client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
            int status = client.executeMethod(postMethod);
            
            if (status == HttpStatus.SC_OK) {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                br = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String str = "";
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }                
                body = stringBuffer.toString();   
            } else {
                body = "fail：" + status;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	if (br != null)
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            // 释放连接
            postMethod.releaseConnection();
        }        
        return body;
    }    
	/*public static void main(String[] args) {
		File file = new File("E:/workspace/Interface4httpClient/docu/办文单.doc");
		System.out.println(fileUpload("http://127.0.0.1:81/HttpUpload/uploadFile?appid=www&path=/dd/bb/cc/ada.doc",file));
	}*/
	
}
